from common import markdown


def read_file(path):
    """
    读取文件内容并返回。

    :param path: 文件路径
    :return: 文件内容列表
    """
    try:
        with open(path, 'r', encoding='utf-8') as file:
            lines = file.readlines()
        return lines
    except Exception as e:
        print(f"读取文件时发生错误: {e}")
        return []


def write_file(path, content):
    """
    将内容写入到指定的文件中。

    :param path: 文件路径
    :param content: 要写入的内容
    """
    try:
        with open(path, 'w', encoding='utf-8') as file:
            file.writelines(content)
        print(f"内容已成功写入到文件: {path}")
    except Exception as e:
        print(f"写入文件时发生错误: {e}")


def process_file(path, params):
    start_keywords, end_keywords, any_keywords, delete_full_lines, replace_keywords = params
    """
    处理文件内容，删除和替换特定行。

    :param path: 文件路径
    :param start_keywords: 要删除的开头行的关键字列表
    :param end_keywords: 要删除的开头行的关键字列表
    :param any_keywords: 要删除的全文中任意行的关键字列表
    :param delete_full_lines: 要删除全文中出现的指定信息的行，从信息出现的位置开始一直到本行结束
    :param replace_keywords: 要替换全文中出现的指定关键字为新的关键字的字典
    """
    lines = read_file(path)
    if not lines:
        return

    # 删除开头的空行
    while lines and (lines[0].strip() == "" or lines[0] == "\n" or lines[0] is None):
        lines.pop(0)

    # 删除第一行以任意一个 start_keywords 开头的行
    while lines and any(lines[0].startswith(kw) for kw in start_keywords):
        lines.pop(0)

    # 删除最后一行为空的行，直到遇到非空行
    while lines and (lines[-1].strip() == "" or lines[-1] == "\n" or lines[-1] is None):
        lines.pop()

    # 删除最后一行以任意一个 end_keywords 开头的行
    while lines and any(lines[-1].strip().startswith(kw) for kw in end_keywords):
        lines.pop()

    # 删除全文中包含任意一个 any_keywords 的行
    lines = [line for line in lines if not any(kw in line for kw in any_keywords)]

    # 删除全文中出现的指定信息的行，从信息出现的位置开始一直到本行结束
    for keyword in delete_full_lines:
        lines = [line if keyword not in line else line[:line.index(keyword)].strip() + '\n' for line in lines]

    # 替换全文中出现的指定关键字为新的关键字
    for old_keyword, new_keyword in replace_keywords.items():
        lines = [line.replace(old_keyword, new_keyword) for line in lines]

    # 写回文件
    write_file(path, lines)


def format_file(path, title):
    """
    格式化指定路径下文件内容
    :param title:
    :param path: 指定路径
    """
    file_list, query_content = markdown.get_from_already_directory_structure(path)
    print(f"文件列表: {file_list}")

    for file in file_list:
        process_file(file, __get_params(title))

    print("处理完成")


def __get_params(title):
    """
    :param title:
    :return: start_keywords, end_keywords, any_keywords, delete_full_lines, replace_keywords
    """
    start_keywords = ["当然", "当然可以"]
    end_keywords = ["希望", "希望这份", "希望这篇", "希望本文", "这份笔记", "如果你有任何", "你可以将上述内容"]
    any_keywords = []
    delete_full_lines = ["希望这份文档", "希望这些内容", "希望这份笔记", "希望对你学习", "希望这份", "如果有任何"]
    replace_keywords = {
        "Markdown": "",
        f"{title} 学习之:": "",
        f"{title}学习之：": "",
        f"{title} 学习：": "",
        f"{title} 学习之：": "",
    }
    return start_keywords, end_keywords, any_keywords, delete_full_lines, replace_keywords
